import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from 'element-plus'
import {
  taskTypeListApi,
  taskTypeStoreApi,
  taskTypeUpdateApi,
  taskTypeDeleteApi,
  taskTypeShowApi,
  taskTypeSelectApi,
  typeSelectApi
} from "@/api/taskApi";
import { userSelectApi } from "@/api/user"
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 20,
    taskTypeId: "",
    name: "",

  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    // {
    //   label: "任务阶段",
    //   prop: "taskType",
    // },
    {
      label: "任务阶段",
      prop: "name",
      minWidth: 120,
    },
    {
      label: "预估时长(天)",
      prop: "duration"
    },
    {
      label: "是否多人",
      prop: "hasMultiUser",
      formatter:(row: any)=> {
        return row.hasMultiUser === 0?'单人':'多人'
      },
    },
    {
      label: "指派用户",
      prop: "assignedUsers",
      slot: "assignedUsers",
      minWidth: 200,
      // formatter:(row: any)=> {
      //   let arr = JSON.parse(row.assignedUsers)
      //   if(arr) {
      //     let userArr = []
      //     for (let item of Object.values(arr)) {
      //       userArr.push(item.username)
      //     }
      //     return userArr
      //   }
      //   return arr
      // },
    },

    {
      label: "关键词",
      prop: "keyword",
    },
    {
      label: "默认描述",
      prop: "description"
    },
    {
      label: "优先级",
      prop: "priority",
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 120
    }
  ];
  function handleSizeChange(val: number) {
    form.page = 1;
    form.perPage = val;
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    onSearch()
  }

  async function onSearch() {
    loading.value = true;
    const res: any = await taskTypeListApi(toRaw(form));
    dataList.value = res?.result?.list;
    pagination.total = res?.result?.total;
    pagination.pageSize = res?.result?.perPage*1;
    pagination.currentPage = res?.result?.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "创建任务", row?: FormItemProps) {
    const userSelect: any = await userSelectApi()
    const taskTypeSelectParent: any = await taskTypeSelectApi()
    const taskTypeSelect: any = await typeSelectApi()
    let children = []
    let listSelect = []
    for (let i = 0; i < taskTypeSelectParent?.result.length; i++) {
      if(taskTypeSelectParent?.result[i].child) {
        for (let row of taskTypeSelectParent?.result[i].child) {
          for (let child of row) {
            children.push(child)
          }
          taskTypeSelectParent.result[i].child = children
        }
      }

    }

    if (`${title}` == "创建任务") {

      formInline.value = {
        title: "创建任务",
        userSelect: userSelect.result,
        taskTypeSelectParent: taskTypeSelectParent.result,
        taskTypeSelect: taskTypeSelect.result,
        hasMultiUser: 0,
        priority: 1,
        parentId: [0],
      };
    } else {
      const res: any = await taskTypeShowApi({ taskTypeId: row.taskTypeId });
      let arrUser: any = Object.values(res?.result?.assignedUsers ?? [])
      let arrUser1 = []
      if(arrUser) {
        for (let item of arrUser) {
          arrUser1.push(item.userId)
        }
      }

      formInline.value = {
        title: "编辑任务",
        userSelect: userSelect.result,
        taskTypeSelect: taskTypeSelect.result,
        taskTypeSelectParent: taskTypeSelectParent.result,
        taskType: res?.result?.taskType ?? "",
        priority: res?.result?.priority ?? "",
        taskTypeId: res?.result?.taskTypeId ?? "",
        hasMultiUser: res?.result?.hasMultiUser ?? "",
        duration: res?.result?.duration ?? "",
        keyword: res?.result?.keyword ?? "",
        description: res?.result?.description ?? "",
        assignedExtraTo: arrUser1,
        parentId: res?.result?.parentId ?? 0,
      };

    }

    addDialog({
      title: `${title}`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;


        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }
        console.log(curData)
        FormRef.validate(valid => {
          if (valid) {
            // if(curData.taskType && curData.taskType.length === 2) {
            //   for (let item of curData.taskType) {
            //     for (let row of curData.taskTypeSelect) {
            //       if(row.childrens && row.childrens.length > 0) {
            //         for (let child of row.childrens) {
            //           if(item === child.taskType) {
            //             curData.parentId = child.parentId
            //           }
            //         }
            //       }
            //     }
            //   }
            // }

            const params = {
              taskTypeId: curData.taskTypeId,
              taskType: curData.taskType[curData.taskType.length - 1],
              priority: curData.priority,
              hasMultiUser: curData.hasMultiUser,
              duration: curData.duration,
              keyword: curData.keyword,
              description: curData.description,
              assignedUsers: curData.assignedExtraTo,
              parentId: curData.parentId[curData.parentId.length - 1],
            }

            if (title === "创建任务") {
              taskTypeStoreApi(toRaw(params)).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }

              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            } else {
              taskTypeUpdateApi(params).then((res: any) => {
                if(res?.code === 200) {
                  chores();
                }
              })
              .catch(error => {
                message(error.response.data.msg ?? "操作失败,请联系管理员", {
                  type: "error"
                });
              });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();

  });

  function handleDelete(row) {
    ElMessageBox.confirm('请继续进行删除操作?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      taskTypeDeleteApi({ taskTypeId: row.taskTypeId }).then((res: any) => {
        if(res?.code === 200) {
          message(`删除成功`, { type: "success" });
          onSearch();
        }
      });
    })
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
  };
}
